package com.mall.product.service.impl;

import com.common.utils.R;
import com.mall.product.dao.SkuImagesDao;
import com.mall.product.entity.SkuImagesEntity;
import com.mall.product.entity.SpuInfoDescEntity;
import com.mall.product.feign.SeckillFeignService;
import com.mall.product.service.*;
import com.mall.product.vo.SeckillVo;
import com.mall.product.vo.SkuItemSaleAttrVo;
import com.mall.product.vo.SpuItemGroupAttrVo;
import com.mall.product.vo.SpuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mall.product.dao.SkuInfoDao;
import com.mall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuInfoDao skuInfoDao;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 信息检索方法
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key)
                        .or().like("sku_name", key);
            });
        }
        String catalogId = (String) params.get("catalogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            wrapper.eq("catalog_id", catalogId);
        }
        if (StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        if (StringUtils.isNotEmpty(min)) {
            wrapper.ge("price", min);
        }
        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal(0)) > 0) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据spuId查询sku
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * 查询item属性
     *
     * @param skuId
     * @return
     */
    @Override
    public SpuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SpuItemVo vo = new SpuItemVo();
        CompletableFuture<SkuInfoEntity> skuInfoEntityCompletableFuture = CompletableFuture.supplyAsync(() -> {
                    SkuInfoEntity skuInfoEntity = this.getById(skuId);
                    vo.setInfo(skuInfoEntity);
                    return skuInfoEntity;
                }
                , threadPoolExecutor);
        CompletableFuture<Void> saleFuter = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSkuSaleAttrValueBySpuId(res.getSpuId());
            vo.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);
        CompletableFuture<Void> spuFuter = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity descEntity = spuInfoDescService.getById(res.getSpuId());
            vo.setDesc(descEntity);
        }, threadPoolExecutor);
        CompletableFuture<Void> groupFuter = skuInfoEntityCompletableFuture.thenAcceptAsync((res) -> {
            List<SpuItemGroupAttrVo> spuItemGroupAttrVo = attrGroupService.getAttrgroupWithSpuId(res.getSpuId(), res.getCatalogId());
            vo.setBaseAttrs(spuItemGroupAttrVo);
        }, threadPoolExecutor);
        CompletableFuture<Void> imageFuter = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
            vo.setImages(skuImagesEntities);
        }, threadPoolExecutor);
        CompletableFuture<Void> seckillFuter = CompletableFuture.runAsync(() -> {
            R session = seckillFeignService.getSecckillSessionBySkuId(skuId);
            SeckillVo seckillVo = (SeckillVo) session.get("data");
            vo.setSeckillVo(seckillVo);
        }, threadPoolExecutor);
        CompletableFuture.allOf(saleFuter, spuFuter, imageFuter, groupFuter,seckillFuter).get();
        return vo;
    }

    @Override
    public List<String> getSkusBySpuId(Long skuId) {
        return this.skuInfoDao.getSkuSaleAttrs(skuId);
    }
}